import asyncio
import json
from curl_cffi import requests
import subprocess
import time
from utils import *


def convert_cookie_dict_to_string(cookie_dict):
    # Join each key-value pair with '=' and then join all pairs with '; '
    cookie_string = '; '.join([f"{key}={value}" for key, value in cookie_dict.items()])
    return cookie_string


def get_h5st(cookie, data):
    cookie = convert_cookie_dict_to_string(cookie)
    try:

        cmd = [
            'node',
            'mh5st514.js',
            "ffb96",
            json.dumps(data),
            cookie
        ]

        result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
        print("STDOUT:", result.stdout)
        print("STDERR:", result.stderr)

        # 只获取h5st的值
        for line in result.stdout.split('\n'):
            if 'h5st==>' in line:
                h5st = line.split('h5st==> ')[1].strip()
                return h5st

        print("未找到h5st值")
        return None

    except Exception as e:
        print(f"Error executing JavaScript: {e}")
        return None
async def make_request_with_retry():

    headers = {
        "accept": "application/json",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
        "cache-control": "no-cache",
        "origin": "https://so.m.jd.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://so.m.jd.com/",
        "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Microsoft Edge\";v=\"138\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0",
        "x-referer-page": "https://so.m.jd.com/ware/search.action",
        "x-rp-client": "h5_1.0.0"
    }
    # cookies = {
    #     "b_webp": "1",
    #     "b_avif": "1",
    #     "jcap_dvzw_fp": "_HIVLiZCIEZDIcHwXjPU43al5uvsYIwPfs4O6VE9nqABptbi3ASG0seWjzU_o2F4bpTtKrH1VphdN9RwziykSA==",
    #     "whwswswws": "",
    #     "__jdv": "122270672%7Cdirect%7C-%7Cnone%7C-%7C1751545604909",
    #     "__jdu": "1751545604909534518369",
    #     "pinId": "briEibRb-h1YgxkG81uaz7V9-x-f3wj7",
    #     "pin": "jd_7eac037a858fc",
    #     "unick": "jd_8js7q5tn2s7n2h",
    #     "_tp": "aO5XtogPiplRTZPyN6P5Vkd5JC%2FQJe7kEmh0g0oTaNI%3D",
    #     "_pst": "jd_7eac037a858fc",
    #     "shshshfpa": "ab96e4b0-82d6-a907-9206-6c096fe807bb-1751545628",
    #     "shshshfpx": "ab96e4b0-82d6-a907-9206-6c096fe807bb-1751545628",
    #     "PCSYCityID": "CN_440000_440300_0",
    #     "autoOpenApp_downCloseDate__jd_czlogin_openapp_": "1752224419174_1",
    #     "b_dw": "1912",
    #     "b_dh": "954",
    #     "b_dpr": "1",
    #     "commonAddress": "0",
    #     "regionAddress": "1%2C72%2C55674%2C0",
    #     "mt_xid": "V2_52007VwMUVl1cV14YSBxUBG8HEFdZWFtYGEEpXVBjCkcCCAhOWBsdGUAAZQAUTg1eVFMDHhoLDDdQEQBeXFBdL0oYXwF7AhROXVhDWhlCHFQOZwMiUG1YYlMfSB1eBmMEFFJcX1ZZGk4RWQ1XAxFRXw%3D%3D",
    #     "warehistory": "\"100124552423,10092745719292,100124552423,100126228944,\"",
    #     "autoOpenApp_downCloseDate_autoOpenApp_autoPromptly": "1752227819923_1",
    #     "TrackID": "1niKUQYb-rtx_W8NqIr7p794udrddHlWmBsM7VCqfFSRqsnFBOKtSNGv5MwSaaIptwAekpQGc-lVbatyIbIIsdh6kB0gSXD0Vf_HOAU3UPpgyNscP-uKG7aFXOVOpu3Hz",
    #     "thor": "2B3FAB022DDA7FFF772855629D82E8BA86B6B654FC776E1930AA7FEB1EB3100E4352BA9EF36DB2CA5363601A26FB8D56926934F02FEC214A855D33E9523DF9BBF6219112C431FBD129D5E5F946C5285F4F5B6BCB9C68A64458D0B167F141477BCC221C42AC5B82E714C37179E720FA1CA416456728D98223977A00EC6720051F59117BA692A7FA2CB8A8C792545F0FC0C1CB9B05CAF59D31B40631A5DF1C0593",
    #     "light_key": "AASBKE7rOxgWQziEhC_QY6yaY-qjKdTSlPyvgw1EnJwRdrY19x9HuXOKE36tg6wrJUawo6E8",
    #     "mba_muid": "1751545604909534518369",
    #     "3AB9D23F7A4B3C9B": "GNWKXUTIE6HBK6NALGSXSPDIJB4FOSTK2HH5HNAWZAUUMF5JYQCGOIB4252C7TECGDOSXSGLUC74Z5SQVPIKNU2LBE",
    #     "wxa_level": "1",
    #     "retina": "0",
    #     "cid": "9",
    #     "jxsid": "17524622261035690925",
    #     "appCode": "ms0ca95114",
    #     "webp": "1",
    #     "__jda": "143920055.1751545604909534518369.1751545604.1752457466.1752462226.6",
    #     "__jdc": "143920055",
    #     "visitkey": "5225087356900709310",
    #     "cd_eid": "jdd03GNWKXUTIE6HBK6NALGSXSPDIJB4FOSTK2HH5HNAWZAUUMF5JYQCGOIB4252C7TECGDOSXSGLUC74Z5SQVPIKNU2LBEAAAAMX7EJXZGIAAAAACAK77ULHDATEXEX",
    #     "3AB9D23F7A4B3CSS": "jdd03GNWKXUTIE6HBK6NALGSXSPDIJB4FOSTK2HH5HNAWZAUUMF5JYQCGOIB4252C7TECGDOSXSGLUC74Z5SQVPIKNU2LBEAAAAMYA3RXRIAAAAAADKWMT623YFK2JAX",
    #     "_gia_d": "1",
    #     "autoOpenApp_downCloseDate_jd_homePage": "1752462226750_1",
    #     "sbx_hot_h": "null",
    #     "x-rp-evtoken": "mGW9U4qbzsaBdCMe70m9pK3F098HjiOOglo64cWymzQJkF6isfGYcjX-Mv12m5c-NH9VVzi6GSqr6uU3KT0pOw%3D%3D",
    #     "flash": "3_gdbg7X_zNB3Xb05nVFDZev9bp4ahAfDsE60zF_zRKcg8CSv2EZGlOQOO_OVx-foQr0tuMlZ4DHwAK_Kdp4BiuEaxy9Fq09VE0BRZsp7Kxzawf2O5ANkB2TZoQ8GEg2pqA2XnnbPnoCJsLjIj-D3I7NHVYahIb0FHnzodnTkddgA1CJw1r6Xtbq**",
    #     "shshshfpb": "BApXSMrHsBf1AYEqgcJFHsyDPBX7ULrZhBhMVUQdr9xJ1MppMe462",
    #     "TrackerID": "54xUReMIukQ4k_oNhQ4BuD47ZE0HhPY2-0eBLzj_dsuJiu1OiPSAYFNlLiWATa8zMOh3mhv127tKXw1kKNS06_ng3P8Uul77ypSv2wvPXE0HTm6dzrcut0bc_nZT0j4I",
    #     "pt_key": "AAJodHPSADDJES1jU_Blhctxha1C7tKOBovDsU8RUzzEXmyrwtx-rmqrT1X7pxwOKMZquUCE4UE",
    #     "pt_pin": "jd_7eac037a858fc",
    #     "pt_token": "wi15c5pw",
    #     "pwdt_id": "jd_7eac037a858fc",
    #     "sfstoken": "tk01m97f51b86a8sM3gxNW8yNjBkKEkYp3Abyr+9xoFC4E3Ai4mUT56NYi5dESwqRoGNm4HE+RhX7tHsEBXrzOhaFNBE",
    #     "wqmnx1": "MDEyNjM1M3Bzam1lcmM/bzYwOSU1RSUuJUUlODhtcm9tPXNvVEhtZ2E3NTU3MGwuaXMxIDQ0cGI1NlRsRylvMzBhLzNnLjAzWWRmNDNWUkRGSCZS",
    #     "__jdb": "143920055.5.1751545604909534518369|6.1752462226",
    #     "autoOpenApp_downCloseDate_auto": "1752462295553_1800000",
    #     "pt_st": "1_8r91NC0EHMaLLoXmfcgEhYkG05UHbB06nDjyy5SPQwpzlVxnUSqcv0QaCTPFGjVpPCZbVM-H8uh1GCiaxzU1zisjAjT0ajEUmjxGowxS4Zah2M0mVgkbnZzh-oIUBi5AgKL2QRDYh9lyOtduCqmXMmUSG4sXsRMrVbGZxrzcWPPa7NXv7vDKACB3ErYjmo4hBLJxm8JYljZMHEaGGaagAf9TtbTmw2G9lOzGaUuM",
    #     "e_wq_addr": "CMU3GzPpDzTpDJU2DzHpCMU3GyV1DJCnDyV1DOVLG18vdJY3CUGvdJu2CzCvdJUzC0PpTXU5HUO2TXU1GtUmTXU1HJu3TXU4ENU3TXU5CNUzXyU3GyV1DJCnDyV1DOVLGyV1DUUmCsV1DtcnHMV1EJYzCyV1DJCzGIV1EUVLDsV1DUS1CMV1DUU5DyV1ENq1DyV1EJK1CyV1DtcnHMV1EJYzCyV1DJO2GyV1DJZPHMU3GzOnDs40ENSyDzYvCuCzEG==",
    #     "wq_addr": "0%7C1_72_55674_0%7C%u5317%u4EAC_%u671D%u9633%u533A_%u9EA6%u5B50%u5E97%u8857%u9053_%7C%u5317%u4EAC%u5E02%u671D%u9633%u533A%u9EA6%u5B50%u5E97%u8857%u9053%u671D%u9633%u516C%u56ED%7C116.482276%2C39",
    #     "jdAddrId": "1_72_55674_0",
    #     "jdAddrName": "%u5317%u4EAC_%u671D%u9633%u533A_%u9EA6%u5B50%u5E97%u8857%u9053_",
    #     "mitemAddrId": "1_72_55674_0",
    #     "mitemAddrName": "%u5317%u4EAC%u5E02%u671D%u9633%u533A%u9EA6%u5B50%u5E97%u8857%u9053%u671D%u9633%u516C%u56ED",
    #     "mba_sid": "1752462226134952135356.6",
    #     "PPRD_P": "UUID.1751545604909534518369",
    #     "jxsid_s_t": "1752462296290",
    #     "jxsid_s_u": "https%3A//so.m.jd.com/ware/search.action",
    #     "sdtoken": "AAbEsBpEIOVjqTAKCQtvQu17mlh81ykk-QBWptVGAH8WMvT2xxRrZiN1IDgQnjCiCnXhgHQRcLuaGgxBU-qQrTz09uL09WZLrm7wghnnI9PqKdpRUhHHgBdbpdOR",
    #     "sc_width": "1920"
    # }
    cookies = await get_and_refresh_cookies(force_refresh=False)
    print("ck:::",cookies)
    # h5st_ck = cookie_dict_to_str(cookies)
    # headers['cookie'] = h5st_ck
    url = "https://api.m.jd.com/api"
    params = {
        "functionId": "searchKeyword",
        "appid": "jd-cphdeveloper-m",
        "body": "{\"tenantCode\":\"jgm\",\"bizModelCode\":5,\"bizModeClientType\":\"M\",\"externalLoginType\":\"1\",\"key\":\"1664 白啤酒11.8°P瓶装330m\",\"datatype\":\"1\",\"page\":\"2\",\"pagesize\":\"10\",\"ext_attr\":\"no\",\"brand_col\":\"no\",\"price_col\":\"no\",\"color_col\":\"no\",\"size_col\":\"no\",\"ext_attr_sort\":\"no\",\"merge_sku\":\"yes\",\"multi_suppliers\":\"yes\",\"area_ids\":\"1,72,55674\",\"filt_type\":\"redisstore,1;\",\"qp_disable\":\"no\",\"debug\":\"false\",\"t1\":\"1752462290734\",\"sourceType\":\"H5_home_page_search\"}",
        "loginType": "2",
        "x-api-eid-token": "jdd03GNWKXUTIE6HBK6NALGSXSPDIJB4FOSTK2HH5HNAWZAUUMF5JYQCGOIB4252C7TECGDOSXSGLUC74Z5SQVPIKNU2LBEAAAAMX7EJXZGIAAAAACAK77ULHDATEXEX",
        "h5st": "20250714110526081;wxazw3p3gwahjw35;ffb96;tk05wc34bc78041lMysyM2hLQlY1smeh7SHUGp4RHhrS7SHQNN3RuueuWUu1NnRY2K7drlbV6qodVZKW4mbWIpbhNtLV;f6d5c0cd269d0ee617d356df816ee917;5.1;1752462320081;t6HsMa7i3FoUNR3V7u3i3FXW2RHmOGLm_VImOuMsCWbiOGLmAh4WMusmk_Mm3moi1q4W2Wbh7ObV_KrhNtri3aYV2WLhLpoVKRLi6qImOGLm_VqTHlYV3lsmOGujMmLW6W4h2m4h_ObgINLiLJrV7K7W9arh9KrV8mYg5qbWMuMgMiXW41YWLlsmOGujMqbjMuMgMebRMlsmOGujMOLj92ch4xZVCJIVPZrUMuMgMWHmOuMsCmcT2mLhXd4e-pImOGLmBxoVApISMusmk_Mm8iLTFRJmOGLmItHmOuMsC6nmOGOiOGLm9qbRMlsmOusmk_Mi9uMgMubi5lImOusmOGuj26sm0mMi9aHWMusmOuMsCmMTPBYV8K5VdhZiYlsm0mcT-dITNlHmOusmOGuj_uMgMObRMlsmOusmk_siOGLm3aHWMusmOuMsCO7iOGLm4aHWMusmOuMsCurm0mch5lImOusmOGuj_uMgMebRMlsmOusmk_ch6uMgMibRMlsmOusmk_Mm52ciAuLmOGLm9aHWMusmOuMsCurm0m8U3lsmOusmk_chOGLm79ImOusmOGuj_uMgM_ImOusmOGuj_uMgMe4RMusmOuMsztMgMeITJdnQJlsmOGujxtsmkm8WINbh2q4h7u7WNZ4hPdIUMuMgMmrSMusmOuMsCm8WINbh2q4h7u7WNZ4hPdIUMuMgMqrSMusmOuMsztMgMunSMusmk_Mm6WrQOCrh42YUXt8g_2si9usZgt8S3xoVAJ4ZMuMgMqYR7lsmOG_Q;7bc7de5c663c046db13775e01b149239;ri_uKJKT-JoRL1YRI9cQKxIWCeYU_tXW"
    }
    h5st = get_h5st(cookie=cookies, data=params)
    print(h5st)
    params['h5st'] = h5st
    proxies = {
        'http': '127.0.0.1:7890',
        'https': '127.0.0.1:7890',
    }
    response = requests.get(url, headers=headers,params=params,proxies=proxies,cookies=cookies)

    print(response.status_code)
    if response.status_code==200:
        return response.json()
    else:
        raise Exception(f"请求失败,响应码：{response.status_code} 响应内容:{response.text}")
async def main():
    demo=await make_request_with_retry()
    print(demo)
if __name__ == '__main__':
    asyncio.run(main())